package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.utils.BeanMapUtils;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {

    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;


    @RequestMapping(value = "/contractList",name = "展示已提交的合同列表数据")
    public String findAll(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer pageSize){

//        查询购销合同 应该有什么条件  companyId   按照生成时间排序 降序
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId()).andStateEqualTo(1);
        example.setOrderByClause("create_time desc");
        PageInfo<Contract> pageInfo = contractService.findAll(example,page,pageSize);
        request.setAttribute("page",pageInfo); //这个 “page” 不能写错，因为页面就是取的是page中的值
        return "cargo/export/export-contractList";
    }

    @RequestMapping(value = "/list",name = "展示报运单列表数据")
    public String list(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer pageSize){

//        查询报运 应该有什么条件  companyId   按照生成时间排序 降序
        ExportExample example = new ExportExample();
        ExportExample.Criteria criteria = example.createCriteria();
        criteria.andCompanyIdEqualTo(getCompanyId());
        example.setOrderByClause("create_time desc");
        PageInfo<Export> pageInfo = exportService.findAll(example,page,pageSize);
        request.setAttribute("page",pageInfo); //这个 “page” 不能写错，因为页面就是取的是page中的值
        return "cargo/export/export-list";
    }


    @RequestMapping(value = "/toExport",name = "进入到填写报运单的页面")
    public String toExport(String id){
        request.setAttribute("id",id);
        return "cargo/export/export-toExport";
    }
    @RequestMapping(value = "/edit",name = "保存报运单的方法")
    public String edit(Export export){

        if(StringUtils.isEmpty(export.getId())){ //表示新增
            export.setId(UUID.randomUUID().toString());
            export.setCompanyId(getCompanyId());
            export.setCompanyName(getCompanyName());
            export.setInputDate(new Date());
            export.setCreateBy(getUser().getId());
            export.setCreateDept(getUser().getDeptId());
            export.setState(0);
            exportService.save(export);
        }else{
            exportService.update(export);
        }
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/toUpdate",name = "进入到修改报运单的页面")
    public String toUpdate(String id){
//        报运单对象和这个报运单下的货物集合
        Export export = exportService.findById(id);
        request.setAttribute("export",export);

        List<ExportProduct> exportProductList  = exportProductService.findByExportId(id);
        request.setAttribute("eps",exportProductList);

        return "cargo/export/export-update";
    }
    @Autowired
    private DownloadUtil downloadUtil;
    @RequestMapping(value = "/exportPdf",name = "下载报运单")
    public void exportPdf(String id) throws Exception {
        //需要报运单以及报运单下面的货物数据
        Export export = exportService.findById(id);
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);
        //读取模板
        String realPath = session.getServletContext().getRealPath("template/export.jasper");
        FileInputStream stream = new FileInputStream(realPath);

        Map<String, Object> mapPdf = BeanMapUtils.beanToMap(export);


        JRBeanCollectionDataSource dataSource=new JRBeanCollectionDataSource(exportProductList);
        JasperPrint jasperPrint = JasperFillManager.fillReport(stream, mapPdf, dataSource);
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
        bos.write(bytes);

        downloadUtil.download(bos,response,"报运单.pdf");

    }
    @RequestMapping(value = "/submit",name = "提交报运单的方法")
    public String submit(String id) {
        Export export = new Export();
        export.setId(id);
        export.setState(1);
        exportService.update(export);
        return "redirect:/cargo/export/list.do";
    }

    @RequestMapping(value = "/exportE",name = "海关电子报运方法")
    public String exportE(String id){  //报运单的id
        Export export = exportService.findById(id);
//        远程报运
        ExportVo exportVo = new ExportVo(); //包含的数据是 报运单+报运单下的货物
        BeanUtils.copyProperties(export,exportVo);
        exportVo.setExportId(id);

//        查询当前报运单下的货物 为了转成 ExportProductVo
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);

        for (ExportProduct exportProduct : exportProductList) {
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo);
            exportProductVo.setEid(id);
            exportProductVo.setExportProductId(exportProduct.getId());
            exportVo.getProducts().add(exportProductVo);
        }
        WebClient.create("http://localhost:9090/ws/export/ep").post(exportVo);

//        应该调用查询方法
        ExportResult exportResult = WebClient.create("http://localhost:9090/ws/export/ep/" + id).get(ExportResult.class);

//        修改报运单的和报运单下货物数据
        exportService.exportE(exportResult);


        return "redirect:/cargo/export/list.do";
    }

}
